<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
class AccountController extends Zend_Controller_Action
{
    public function init()
    {
    /* Initialize action controller here */
    }
    
    public function indexAction()
    {
    // action body
    }

    /**
    * Process the account form.
    *
    */
//    public function successAction()
//    {
////        $email = $this->_request->getParam('email');
////        $username = $this->_request->getParam('username');
////        $password = $this->_request->getParam('password');
//        if ($this->_request->isPost())
//        {
//            $email = $this->_request->getPost("email");
//            $username = $this->_request->getPost("username");
//            $password = $this->_request->getPost("password");
//
//            require_once '../aplication/models/SaveAccount.php';
//            $SaveAccount = new SaveAccount();
//            $SaveAccount->saveAccount($username, $password, $email);
//        }
//        else
//        {
//            throw new Exception("Disculpa, ocurrio un error al intentar enviar el formulario ... XD");
//        }
//
//    // action body
//    }

     /**
    * Process new account form.
    *
    */
//    public function success1Action()
//    {
//        $form = $this->getSignupForm();
//        //Check if the submitted data is POST type
//        if($form->isValid($_POST))
//        {
//            $email = $form->getValue("email");
//            $username = $form->getValue("username");
//            $password = $form->getValue("password");
//
//        //Save the user into the system.
//        }
//        else
//        {
////            throw new Exception("Whoops. Wrong way of submitting your information.");
////            $this->view->errors = $form->getErrorMessages();
////
////LA VALIDACION TAMBIEN SUCEDE EN          $usernameElement->setOrder(1)->setRequired(true);
////en getSignupForm()
//            $this->view->errors = $form->getMessages();
//            $this->view->form = $form;
//
//        }
//    }

    /**
    * Process Sign up Form.
    *
    */
    public function successAction()
    {
        //Get the signup form
        $form = $this->getSignupForm();
        //Check if the submitted data is POST type
        if($form->isValid($_POST))
        {
            $email = $form->getValue("email");
            $username = $form->getValue("username");
            $password = $form->getValue("password");
            //Set the database parameters as described in Chapter 5
            try
            {
                //Save the user to the database as described in Chapter 5
                //Send out the welcome email.
                $config = array('auth' => 'login',
                                'ssl' => 'tls',
                                'username' => 'dcubas16@gmail.com',
                                'password' => 'depeche11',
                                'port' => '587');
                $transport = new Zend_Mail_Transport_Smtp('smtp.gmail.com',$config);
                $MailObj = new Zend_Mail();
                $emailMessage = " Welcome to LoudBite.com.";
                $fromEmail = "welcomeparty@loudbite.com";
                $fromFullName = "LoudBite.com";

                $to = $email;
                $subject = "Welcome to LoudBite.com";
                
                $validator = new Zend_Validate_EmailAddress( Zend_Validate_Hostname::ALLOW_DNS,true);
                if($validator->isValid($to))
                {
                    $MailObj->setBodyText($emailMessage);
                    $MailObj->setFrom($fromEmail, $fromFullName);
                    $MailObj->addTo($to);
                    $MailObj->setSubject($subject);

                    try
                    {
                        $MailObj->send($transport);
                        echo "Email enviado correctamente";
                    }
                    catch(Zend_Mail_Exception $e)
                    {
                        //Your Error message here.
                        echo $e->getMessage();
                    }

//                    $MailObj->send($transport);
//
//                    echo "MUY BIEN";
                }
                else
                {
                    //Messages in array.
                    $messages = $validator->getMessages();
                    foreach($messages as $message){echo $message.'<br/>';}
                }
                
                
            }
            catch(Zend_Db_Exception $e)
            {
                echo $e->getMessage();
            }
        }
        else
        {
            $this->view->errors = $form->getMessages();
            $this->view->form = $form;
        }
    }


    /**
    * Display the form for signing up.
    *
    */

//    public function newAction()
//    {
//    // action body
////        $form = new Zend_Form();
////        $form->setAction("succes");
////        $form->setMethod("post");
////        $form->setDescription("sign up form");
////        $form->setAttrib("sitename","loudbite");
////        $this->view->form = $form;
//        $form = new Zend_Form();
//        $form->setAction("succes");
//        $form->setMethod("post");
//        $form->setDescription("sign up form");
//        $form->setAttrib("sitename","loudbite");
//
//       //Create Username Field.
//        $form->addElement('text', 'username');
//        $usernameElement = $form->getElement('username');
//        $usernameElement->setLabel('Username:');
//        $usernameElement->setOrder(1);
//
//        //Create Email Field.
//        $form->addElement('text', 'email');
//        $emailElement = $form->getElement('email');
//        $emailElement->setLabel('Email:');
//        $emailElement->setOrder(2);
//
//        //Create Password Field.
//        $form->addElement('password', 'password');
//        $passwordElement = $form->getElement('password');
//        $passwordElement->setLabel('Password:');
//        $passwordElement->setOrder(3);
//
//        //Create Button.
//        $form->addElement('submit', 'submit');
//        $submitButton = $form->getElement('submit');
//        $submitButton->setLabel('Create My Account!');
//        $submitButton->setOrder(4);
//
//        //Add the form to the view
//        $this->view->form = $form;
//
//        //ADEMAS DEBES PONER UN ECHO EN LA PAGINA PARA QUE SALGA ... XD
//
//    }

    public function newAction()
    {
        //Get the form.
        $form = $this->getSignupForm();
        //Add the form to the view
        $this->view->form = $form;
    }

    /**
    * Activate Account. Used once the user
    * receives a welcome email and decides to authenticate
    * their account.
    *
    */
    public function activateAction()
    {
        $email = $this->_request->getQuery("email");
    // action body
    }

    public function updateAction()
    {
//        $view = new Zend_view();
//        $view->setScriptPath('../application/views/scripts/');
//        $view->render("/account/update.phtml");

        //Check if the user is logged in
        //Fetch the user's id
        //Fetch the users information
        //Create the form.
        $form = $this->getUpdateForm();
        //Check if the form has been submitted.
        //If so validate and process.
        if($_POST)
        {
            //Check if the form is valid.

            if($form->isValid($_POST))
            {
                //Get the values
                $username = $form->getValue('username');
                $password = $form->getValue('password');
                $email = $form->getValue('email');
                $aboutMe = $form->getValue('aboutme');
                //Save.
                $form->avatar->receive();

            }
            //Otherwise redisplay the form.
            else
            {
                $this->view->form = $form;
            }
        }
        //Otherwise display the form.
        else
        {
            $this->view->form = $form;
        }

    }

    /**
    * Create the sign up form.
    */
    private function getSignupForm()
    {
        //Create Form
        $form = new Zend_Form();
        $form->setAction('success');
        $form->setMethod('post');
        $form->setAttrib('sitename', 'loudbite');
        //Add Elements
        //Create Username Field.
        $form->addElement('text', 'username');
        $usernameElement = $form->getElement('username');
        $usernameElement->setLabel('Username:');
        $usernameElement->setOrder(1)->setRequired(true);

        $usernameElement->addValidator(new Zend_Validate_StringLength(6,20));
        $usernameElement->addFilter(new Zend_Filter_StringToLower());
        $usernameElement->addFilter(new Zend_Filter_StripTags());

        //Create Email Field.
        $form->addElement('text', 'email');
        $emailElement = $form->getElement('email');
        $emailElement->setLabel('Email:');
        $emailElement->setOrder(3)->setRequired(true);
        $emailElement->addValidator(new Zend_Validate_EmailAddress());
        $emailElement->addFilter(new Zend_Filter_StripTags());

        //Create Password Field.
        $form->addElement('password', 'password');
        $passwordElement = $form->getElement('password');
        $passwordElement->setLabel('Password:');
        $passwordElement->setOrder(2)->setRequired(true);
        $passwordElement->addValidator(new Zend_Validate_StringLength(6,20));
        $passwordElement->addFilter(new Zend_Filter_StripTags());

        //Create Password Field.

//        $textAreaElement = new Zend_Form_Element_TextArea('aboutme');
//        $textAreaElement->setLabel('About Me:');
//        $textAreaElement->setAttribs(array('cols' => 15,
//        'rows' => 5));
//        $textAreaElement->setOrder(5)->setRequired(true);
//        $form->addElement($textAreaElement);
        //Add Captcha
        $captchaElement = new Zend_Form_Element_Captcha
        (
        'signup',
        array('captcha' => array(
        'captcha' => 'Figlet',
        'wordLen' => 6,
        'timeout' => 600))
        );
        $captchaElement->setLabel('Please type in the
        words below to continue');
        $form->addElement($captchaElement);

        

        $form->addElement('submit', 'submit');
        $submitButton = $form->getElement('submit');
        $submitButton->setLabel('Create My Account!');
        $submitButton->setOrder(5);
        return $form;
    }

    private function getUpdateForm()
    {
        //Create Form
        $form = new Zend_Form();
        $form->setAction('update');
        $form->setMethod('post');
        $form->setAttrib('sitename', 'loudbite');
        $form->setAttrib('enctype', 'multipart/form-data');

        //Load Elements class
        require "../application/models/Form/Elements.php";
        $LoudbiteElements = new Elements();
        //Create Username Field.
        $form->addElement($LoudbiteElements->getUsernameTextField());
        //Create Email Field.
        $form->addElement($LoudbiteElements->getEmailTextField());
        //Create Password Field.
        $form->addElement($LoudbiteElements->getPasswordTextField());
        //Create Text Area for About me.
        $form->addElement($LoudbiteElements->getAboutMeTextArea());

//        $form->addElement($LoudbiteElements->getHiddenText());

//        $form->addElement($LoudbiteElements->getRadioButton());

//        $form->addElement($LoudbiteElements->getCheckBox());

        $fileUploadElement = new Zend_Form_Element_File('avatar');
        $fileUploadElement->setLabel('Your Avatar:');
        $fileUploadElement->setDestination('../public/users');
        $fileUploadElement->addValidator('Count', false, 1);
        $fileUploadElement->addValidator('Extension', false, 'jpg,gif');
        $form->addElement($fileUploadElement);

        //Create a submit button.
        $form->addElement('submit', 'submit');
        $submitElement = $form->getElement('submit');
        $submitElement->setLabel('Actualizo esto');
        return $form;
    }

    public function testConnAction()
    {
        try
        {
            $connParams = array("host" => "localhost"
                                ,"port" => "3306"
                                ,"username" => "root"
                                ,"password" => ""
                                ,"dbname" => "zendaplicacion");
            $db = new Zend_Db_Adapter_Pdo_Mysql($connParams);
        }
        catch(Zend_Db_Exception $e)
        {
            echo $e->getMessage();
        }
        echo "Database object created.";
        //Turn off View Rendering.
        $this->_helper->viewRenderer->setNoRender();

    }

    public function testInsertAction()
    {
        try
        {
            //Create a DB object
            require_once "../application/models/Db/Db_Db.php";
            $db = Db_Db::conn();

            //DDL for initial 3 users
            $statement = "INSERT INTO accounts(username, email, password,status, create_date)
            VALUES('test_1', 'test@loudbite.com', 'password','active', NOW())";
            $statement2 = "INSERT INTO accounts(username,email,password,status,created_date)
            VALUES('test_2', 'test2@loudbite.com', 'password','active', NOW())";
            $statement3 = "INSERT INTO accounts(username,email,password,status,created_date)
            VALUES (?, ?, ?, ?, NOW())";

            //Insert the above statements into the accounts.
            $db->query($statement);
            $db->query($statement2);

            //Insert the statement using ? flags.
            $db->query($statement3, array('test_3', 'test3@loudbite.com','password', 'active'));

            //Close Connection
            $db->closeConnection();
            echo "Completed Inserting";
        }
        catch(Zend_Db_Exception $e)
        {
            echo $e->getMessage();
        }
            //Supress the View.
        $this->_helper->viewRenderer->setNoRender();
    }

    /**
* Test Insert Method
* Insert data into table using insert()
*/
    public function testInsertMethodAction()
    {
        try
        {
            //Create a DB object
            require_once "../application/models/Db/Db_Db.php";

            $db = Db_Db::conn();
            //Data to save.
            $userData1 = array("username" => 'test_4',"email"=> 'test4@loudbite.com',"password" => 'password',
                               "status" => 'active',"created_date" => '0000-00-00 00:00:00');
            $userData2 = array("username" => 'test_5',"email"=> 'test5@loudbite.com',"password" => 'password',
                               "status" => 'active',"created_date"=> '0000-00-00 00:00:00');
            $userData3 = array("username" => 'test_6',"email"=> 'test6@loudbite.com',"password" => 'password',
                               "status" => 'active',"created_date"=> '0000-00-00 00:00:00');
            //Insert into the Accounts.
            $db->insert('accounts', $userData1);
            $db->insert('accounts', $userData2);
            $db->insert('accounts', $userData3);
            //Close Connection
            $db->closeConnection();
            echo "Completed Inserting";
        }
        catch(Zend_Db_Exception $e)
        {
            echo $e->getMessage();
        }
        //Supress the View
        $this->_helper->viewRenderer->setNoRender();
    }

/**
* Test Expression
* Using Database Expressions.
*/
    public function testExpressionAction()
    {
        try
        {
            //Create a DB object
            require_once "../application/models/Db/Db_Db.php";
            $db = Db_Db::conn();
            //Data to save.
            $userData = array(  "username" => 'test_7'
                                ,"email"=> 'test7@loudbite.com'
                                ,"password" => 'password'
                                ,"status" => 'active'
                                ,"created_date"=> new Zend_Db_Expr("NOW()")
                            );
            //Insert into the accounts.
            $db->insert('accounts', $userData);
            //Close Connection
            $db->closeConnection();
            echo "Completed Inserting";
        }
        catch(Zend_Db_Exception $e)
        {
            echo $e->getMessage();
        }
        //Supress the View
        $this->_helper->viewRenderer->setNoRender();
    }


    /**
    * Test Quote
    */
    public function testQuoteAction()
    {
        try
        {
            //Create Db object
            require_once "../application/models/Db/Db_Db.php";
            $db = Db_Db::conn();

            $username = "testing ' user";
            $usernameAfterQuote = $db->quote($username);
            echo "BEFORE QUOTE: $username<br>";
            echo "AFTER QUOTE: $usernameAfterQuote<br>";
            //DDL for initial 3 users
            echo $statement = "INSERT INTO accounts(username, email, password, status, created_date) VALUES($usernameAfterQuote, 'test8@loudbite.com', 'password','active', NOW())";
            //Insert the above statements into the accounts.
            $db->query($statement);
            //Close Connection
            $db->closeConnection();
            echo "Successfully inserted.";
        }
        catch(Zend_Db_Exception $e)
        {
            echo $e->getMessage();
        }
        //Supress the View.
        $this->_helper->viewRenderer->setNoRender();
    }

    /**
    * Test Last Insert
    */
    public function testLastInsertAction()
    {
        try
        {
            //Create Db object
            require_once "../application/models/Db/Db_Db.php";
            $db = Db_Db::conn();
            //Data to save.
            $userData = array("username" => 'testinguser10'
                            ,"email"=> 'test10@loudbite.com'
                            ,"password" => 'password'
                            ,"status"=> 'active'
                            ,"created_date" => new Zend_Db_Expr("NOW()"));
            $db->insert('accounts', $userData);
            //Retrieve the id for the new record and echo
            $id = $db->lastInsertId();
            echo "Last Inserted Id: ".$id."<br>";
            //Close Connection
            $db->closeConnection();
            echo "Successfully Inserted Data";
        }
        catch(Zend_Db_Exception $e)
        {
            echo $e->getMessage();
        }
        //Supress the View.
        $this->_helper->viewRenderer->setNoRender();
    }


//    public function viewAllAction()
//    {
//        //Create Db Object
//        require_once "../application/models/Db/Db_Db.php";
//        $db = Db_Db::conn();
//        try
//        {
//            //Create the SQL statement to select the data.
//            $statement = "SELECT id, username, created_date
//                            FROM accounts
//                            WHERE status = 'active'";
//            //Fetch the data
//            $results = $db->fetchAll($statement);
//            //Set the view variable.
//            $this->view->members = $results;
//        }
//        catch(Zend_Db_Exception $e)
//        {
//            echo $e->getMessage();
//        }
//    }
    public function viewAllAction()
    {
        //Create Db Object
        require_once "../application/models/Db/Db_Db.php";
        $db = Db_Db::conn();
        try
        {
            //Create the SQL statement to select the data.
            $statement = "SELECT id, username, created_date FROM accounts
                          WHERE status = 'active'";
            //Fetch the data
            $results = $db->fetchAll($statement);
            //Create the SQL statement to
            //fetch the COUNT of all active members.
            $statement = "  SELECT COUNT(id) as total_members
                            FROM accounts
                            WHERE status = 'active'";
            //Fetch ONLY the count of active members.
            $count = $db->fetchOne($statement);
            //Set the view variable.
            $this->view->members = $results;
            $this->view->totalMembers = $count;
        }
        catch(Zend_Db_Exception $e)
        {
            echo $e->getMessage();
        }
    }

    public function authenticateAction()
    {
        $form = $this->getLoginForm();
        //Check if there were no errors
        if($form->isValid($_POST))
        {
            //Initialize the variables
            $email = $form->getValue('email');
            $password = $form->getValue('password');
            try
            {
                //Create a db object
                require_once "../application/models/Db/Db_Db.php";
                $db = Db_Db::conn();
                $email = $db->quote($email);
                $password = $db->quote($password);

                //Initialize data to save into DB
                $statement = "SELECT count(*) FROM accounts WHERE EMAIL=".$email." AND PASSWORD=".$password." ";
//                echo $statement;
                $results = $db->fetchOne($statement);

                If ($results == 0)
                {
                    echo "El Usuario no existe";
                }
                Else If ($results == 1)
                {
                    $statement = "SELECT id, username, created_date FROM accounts 
                        WHERE email = ".$email."  AND password = ".$password." ";
//                    echo $statement;
                    $results = $db->fetchRow($statement);

//                    echo "Bienvenido Sr@: ".$email;
                    //Set the user's session
                    $_SESSION['id']= $results['id'];
                    $_SESSION['username'] = $results['username'];
                    $_SESSION['dateJoined'] = $results['created_date'];
                    //Forward the user to the profile page
                    $this->_forward("accountmanager");

                }
//                $this->view->form = $form;

            }
            catch(Zend_Db_Exception $e)
            {
                echo $e->getMessage();
            }
        }
        else
        {
            echo "ESTO ESTA MAL <br>";
            $this->view->errors = $form->getMessages();
            $this->view->form = $form;
        }

    }

/**
* Account Manager.
*
*/
public function accountmanagerAction()
{
    //Check if the user is logged in
    if(!isset($_SESSION['id']))
    {
        $this->_forward("login");
    }
    try
    {
        //Create a db object
        require_once "../application/models/Db/Db_Db.php";
        $db = Db_Db::conn();
        //Initialize data.
        $userId = $_SESSION['id'];
        $userName = $_SESSION['username'];
        $dateJoined = $_SESSION['dateJoined'];
        //Fetch all the users favorite artists.
        $statement = "SELECT b.artist_name, b.id,
                    aa.created_date as date_became_fan
                    FROM artist AS b
                    INNER JOIN accounts_artists aa ON aa.artist_id = b.id
                    WHERE aa.account_id = ?
                    AND aa.is_fav = 1";
        $favArtists = $db->fetchAll($statement, $userId);
        //Set the view variables
        $this->view->artists = $favArtists;
        $this->view->username = $userName;
        $this->view->dateJoined = $dateJoined;
    }
    catch(Zend_Db_Exception $e)
    {
        echo $e->getMessage();
    }
}



    private function getLoginForm()
    {
        //Create the form
        $form = new Zend_Form();
        $form->setAction("authenticate");
        $form->setMethod("post");
        $form->setName("loginform");
        //Create text elements
        $emailElement = new Zend_Form_Element_Text("email");
        $emailElement->setLabel("Email: ");
        $emailElement->setValue("test5@loudbite.com");
        $emailElement->setRequired(true);
        //Create password element
        $passwordElement = new
        Zend_Form_Element_Password("password");
        $passwordElement->setLabel("Password: ");
        $passwordElement->setRequired(true);
        //Create the submit button
        $submitButtonElement = new
        Zend_Form_Element_Submit("submit");
        $submitButtonElement->setLabel("Log In");
        //Add Elements to form
        $form->addElement($emailElement);
        $form->addElement($passwordElement);
        
        $form->addElement($submitButtonElement);
        return $form;
    }

    /**
    * Load the Login Form.
    *
    */
    public function loginAction()
    {
    //Initialize the form for the view.
        $this->view->form = $this->getLoginForm();
    }

    /**
    * Example- Delete Specific Account.
    *
    */
    public function testDeleteAction()
    {
        require_once "../application/models/Db/Db_Db.php";
        $db = Db_Db::conn();
        try
        {
            //Delete the record with
            //username = 'testinguser9' AND status = 'active'
            $conditions[] = "username = 'testinguser9'";
            $conditions[] = "status = 'active'";
            //Execute the query.
            $results = $db->delete('accounts', $conditions);
            //If the execution deleted 1 account then show success.
            if($results == 1)
            {
                echo "Successfully Deleted Single Record.";
            }
            else
            {
                echo "Could not find record.";
            }
        }
        catch(Zend_Db_Exception $e)
        {
            echo $e->getMessage();
        }
        //Supress the View.
        $this->_helper->viewRenderer->setNoRender();
    }

    /**
    * Example - Update Account
    *
    */
    public function testUpdateAction()
    {
        require_once "../application/models/Db/Db_Db.php";
        $db = Db_Db::conn();
        try
        {
            //Update the account 'test_1'
            //Set the email to exampleupdate@loudbite.com
            $conditions[] = "username = 'test_4'";
            $conditions[] = "status = 'active'";
            //Updates to commit
            $updates = array("email" => 'exampleupdate@loudbite.com');
            $results = $db->update('accounts',$updates,$conditions);

            if($results == 1)
            {
                echo "Successfully Updated Record.";
            }
            else
            {
                echo "Could not update record.";
            }
        }
        catch(Zend_Db_Exception $e)
        {
            echo $e->getMessage();
        }
        //Supress the View.
        $this->_helper->viewRenderer->setNoRender();
    }

    /**
    * Save Artist to Db
    *
    */
    public function saveArtistAction()
    {
        //Create instance of artist form.
        $form = $this->getAddArtistForm();
        //Check for logged in status
        if(!isset($_SESSION['id']))
        {
            $this->_forward("login");
        }
        //Check if there were no errors
        if($form->isValid($_POST))
        {
            //Initialize the variables
            $artistName = $form->getValue('artistName');
            $genre = $form->getValue('genre');
            $rating = $form->getValue('rating');
            $isFav = $form->getValue('isFav');
            //Set the temporary account id to use.
            $userId = $_SESSION['id'];
            //Create a db object
            require_once "../application/models/Db/Db_Db.php";
            $db = Db_Db::conn();
            $db->beginTransaction();
            try
            {
                //Initialize data to save into DB
                $artistData = array("artist_name" => $artistName,"genre"=> $genre,
                                    "created_date" =>new Zend_Db_Expr("NOW()"));
                //Insert the artist into the Db
                $db->insert('artists', $artistData);
                //Fetch the artist id
                $artistId = $db->lastInsertId();
                //Initialize data for the account artists table
                $accountArtistData = array("account_id" => $userId,"artist_id" => $artistId,
                                            "rating"=> $rating,"is_fav"=> $isFav,
                                            "created_date" =>new Zend_Db_Expr("NOW()"));
                //Insert the data.
                $db->insert('accounts_artists', $accountArtistData);
                $db->commit();
            }
            catch(Zend_Db_Exception $e)
            {
                //If there were errors roll everything back.
                $db->rollBack();
                echo $e->getMessage();
            }
        }
        else
        {
            $this->view->errors = $form->getMessages();
            $this->view->form = $form;
        }
    }


}

?>
